package com.zxinlee.order.tcc.impl;

import com.zxinlee.order.entity.Order;
import com.zxinlee.order.mapper.OrderMapper;
import com.zxinlee.order.tcc.OrderTccAction;
import com.zxinlee.order.tcc.ResultHolder;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Component
public class OrderTccActionImpl implements OrderTccAction {

    @Autowired
    private OrderMapper orderMapper;

    @Transactional
    @Override
    public boolean prepare(BusinessActionContext businessActionContext,
                           Long orderId, Long userId, Long productId, Integer count, BigDecimal money) {
        //冻结状态为0
        orderMapper.create(new Order(orderId, userId, productId, count, money, 0));

        //一阶段成功,添加成功标记  两层Map指向标记 {StorageTccAction.class : {事务ID : "p"}}
        ResultHolder.setResult(OrderTccAction.class, businessActionContext.getXid(), "p");

        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext businessActionContext) {

        //二阶段执行之前,判断
        //如果没有标记 防止重复commit
        if (ResultHolder.getResult(OrderTccAction.class, businessActionContext.getXid()) == null)
            return true;

        //businessActionContext对象先变为json,再向第二阶段传递,会丢失类型信息
        //取出的orderId可能是Integer,也可能是Long
        //从上下文对象取出orderId,并强转为Long类型
        Long orderId = Long.valueOf(businessActionContext.getActionContext("orderId").toString());
        //修改状态为1
        orderMapper.updateStatus(orderId, 1);

        //第二阶段完成时,删除标记 依据Map的两层key值找到标记
        ResultHolder.removeResult(OrderTccAction.class, businessActionContext.getXid());

        return true;
    }

    @Transactional
    @Override
    public boolean rollback(BusinessActionContext businessActionContext) {

        //二阶段执行之前,判断
        //如果没有标记 防止重复rollback
        if (ResultHolder.getResult(OrderTccAction.class, businessActionContext.getXid()) == null)
            return true;

        Long orderId = Long.valueOf(businessActionContext.getActionContext("orderId").toString());
        orderMapper.deleteById(orderId);

        //第二阶段完成时,删除标记 依据Map的两层key值找到标记
        ResultHolder.removeResult(OrderTccAction.class, businessActionContext.getXid());

        return true;
    }
}
